#include <json/json.h>
#include <iostream>
#include <sstream>
#include <string>
#include <memory>

bool Serialize(const Json::Value &root, std::string &out)
{
    Json::StreamWriterBuilder writer;//这是一个工厂类
    writer.settings_["emitUTF8"] = true;
    std::unique_ptr<Json::StreamWriter> jsonWriter(writer.newStreamWriter());
    std::stringstream ss;
    int ret = jsonWriter->write(root, &ss);
    if (ret!=0)
    {
        std::cout<<"Json::StreamWriter::write() failed"<<std::endl;
        return false;
    }
    out  = ss.str();
    return true;
}
bool UnSerialize(const std::string &in, Json::Value &root)
{
    Json::CharReaderBuilder reader;
    std::unique_ptr<Json::CharReader> jsonReader(reader.newCharReader());
    std::string errs;
    bool ret = jsonReader->parse(in.c_str(), in.c_str()+in.size(), &root, &errs);
    if (!ret || !errs.empty())
    {
        std::cout<<"Json::CharReader::parse() failed"<<std::endl;
        return false;
    }
    return true;
}
int main()
{
    char name[] = "John";
    int age = 25;
    float score[3] = {100, 90, 80};
    Json::Value stu;
    stu["姓名"] = name;
    stu["年龄"] = age;
    stu["成绩"].append(score[0]);
    stu["成绩"].append(score[1]);
    stu["成绩"].append(score[2]);
    std::string out;
    if (!Serialize(stu, out))
    {
        std::cout<<"Serialize failed"<<std::endl;
        return -1;
    }
    std::cout<<out<<std::endl;

    Json::Value root;
    if (!UnSerialize(out, root))
    {
        std::cout<<"UnSerialize failed"<<std::endl;
        return -1;
    }
    std::cout<<root["姓名"].asString()<<std::endl;
    std::cout<<root["年龄"].asInt()<<std::endl;
    int sz = root["成绩"].size();
    for (int i=0; i<sz; i++)
    {
        std::cout<<root["成绩"][i].asFloat()<<std::endl;
    }

    return 0;
}